package cn.wolfcode.luowowo.wensite.util;

import org.springframework.boot.web.servlet.server.Session;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    //存入cookie
    public static void addCookie(HttpServletResponse response, String token, String value, int time) {
        //4,将token送到浏览器中,并将用户的缓存在redis中的信息保存
        Cookie cookie = new Cookie("token", value);
        //4.1设置共享路径,配置"/"是设置根路径,表示任意请求都可以共享cookie中的数据
        cookie.setPath("/");
        //设置有效时间,设置用户缓存在cookie中的有效时间
        cookie.setMaxAge(time);
        response.addCookie(cookie);
    }

    //取出cookie
    public static String getCookie(HttpServletRequest request) {
        //获取所有cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            //遍历所有cookie
            for (Cookie cookie : cookies) {
                //找到需要的cookie
                if (cookie.getName().equals("token")) {
                    //放回我们需要的cookie
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
